// 填报工人工费申请单
import { useState } from "react";
import { View } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import { useMap, useMount, useReactive, useUpdateEffect } from "ahooks";

import ByTag from "@/components/ui/ByTag";
import ByRow from "@/components/ui/ByRow";
import ByCol from "@/components/ui/ByCol";
import Page from "@/components/common/Page";
import ByCell from "@/components/ui/ByCell";
import Card from "@/components/common/Card";
import ByText from "@/components/ui/ByText";
import BySpace from "@/components/ui/BySpace";
import TabsTag from "@/components/app/TabsTag";
import ByButton from "@/components/ui/ByButton";
import Uploader from "@/components/app/Uploader";
import ByCellGroup from "@/components/ui/ByCellGroup";
import FormInput from "@/components/common/FormInput";
import ByStepsItem from "@/components/ui/ByStepsItem";
import ByImageGroup from "@/components/ui/ByImageGroup";
import CustomerCard from "@/components/app/CustomerCard";
import Attendance from "@/packageProject/components/Attendance";
import FormInputNumber from "@/components/common/FormInputNumber";

import ApiCrm from "@/api/crm";
import ApiFinance from "@/api/finance";
import ApiWorkflow from "@/api/workflow";

import useList from "@/hooks/useList";
import useForm from "@/hooks/useForm";
import useFetch from "@/hooks/useFetch";
import useWorkflowDefinition from "@/hooks/useWorkflowDefinition";

import { WorkerAttendanceRecord } from "@/types/attendance";


const tagProps = {
  variant: "outline",
  size: "small",
} as const;

const RowTitle = ({
  title,
  noMargin,
}: {
  title: string;
  noMargin?: boolean;
}) => {
  return (
    <View className={`${noMargin ? "" : "mb-3"} text-third text-sm`}>
      {title}
    </View>
  );
};

type WorkerPayItems = {
  workerId: number | undefined;
  workerName: string;
  amount: number | undefined | "";
  files: string[];
};

type Model = {
  remark: string;
  files: string[];
  intentCustomerId: number;
  constructionProjectName: string;
  applyItems: Array<{
    files: string[];
    workerType: string;
    templateDetailId: number;
    workerPayItems: WorkerPayItems[];
  }>;
};

const WorkerPayItem = ({
  source,
  attendance,
}: {
  source: WorkerPayItems;
  attendance?: WorkerAttendanceRecord;
}) => {
  const model = useReactive(source);

  return (
    <ByRow className="mt-3" align="center">
      <ByCol span={3}>{source.workerName}</ByCol>
      <ByCol span={5}>
        <FormInputNumber
          prefix="¥"
          precision={2}
          placeholder="输入金额"
          defaultValue={model.amount}
          onChange={(e) => (model.amount = e)}
        />
      </ByCol>
      <ByCol span={4} className="pl-1">
        <Attendance source={attendance} />
      </ByCol>
    </ByRow>
  );
};

// 表单校验规则
const rules = {
  applyItems: {
    type: "array",
    defaultField: {
      type: "object",
      fields: {
        workerPayItems: {
          type: "array",
          defaultField: {
            type: "object",
            fields: {
              amount: {
                type: "number",
                required: true,
                validator(rule, value = 0, callback, data) {
                  if (value == 0)
                    callback(new Error(`请输入${data.workerName}的金额`));
                  else callback();
                },
              },
            },
          },
        },
      },
    },
  },
};

export default () => {
  const { params } = useRouter<{
    templateId: string
    workerType: string;
    intentCustomerId: `${number}`;
  }>();

  const workerType = decodeURIComponent(params.workerType || '')
  const intentCustomerId = Number(params.intentCustomerId);

  useMount(() => {
    Taro.setNavigationBarTitle({ title: workerType + '-工人工费' })
  })

  const [index, setIndex] = useState(0)
  const { list } = useList<any>(ApiFinance.getWorkerPaymentTemplateDetails, {
    defaultParams: [{ templateId: Number(params.templateId), intentCustomerId }],
    onAfter: ({ list }) => ({ list: list.map((e: any) => ({ ...e, label: e.itemName })) })
  })


  // 考勤记录Map对象
  const [, attendanceMapHandler] = useMap<any, any>();
  useFetch(ApiCrm.getWorkerAttendanceRecord, {
    defaultParams: [{ intentCustomerId }],
    onSuccess({ workerAttendanceRecordList: list }) {
      list?.forEach((item) => attendanceMapHandler.set(item.workerId, item));
    },
  });

  // 提交表单
  const { loading, model, setModel, submit } = useForm<Model>(
    ApiWorkflow.batchPayrollApply,
    {
      // @ts-expect-error
      rules,
      defaultModel: {
        intentCustomerId,
        constructionProjectName: workerType + "阶段",
        applyItems: [],
        remark: "",
      },
      onSuccess(res) {
        Taro.showToast({ title: "操作成功！" });
        console.log("res", res)
        setTimeout(() => {
          Taro.redirectTo({ url: `detail?wl_id=${res.workflowInstanceIds[0]}` });
        }, 1500);
      },
    }
  );


  // 客户详情
  const { data } = useFetch(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId }],
    onAfter: (res: any) => res.intentCustomer,
  });

  // 获取审批流节点信息
  const [workflowList] = useWorkflowDefinition({ typeCode: "FI_PayrollApply" });

  // 更新图片
  const updatePics = (index: number, pics: string[]) => {
    const item = model.applyItems[index];
    const files = item.files || [];
    item.files = files.concat(pics);
    setModel({ applyItems: [...model.applyItems] });
  };
  // 删除图片
  // 注意：这里的index是applyItems的索引，而不是workerPayItems的索引
  const deleltePics = (index: number, pics: string[]) => {
    const item = model.applyItems[index];
    item.files = pics;
    setModel({ applyItems: [...model.applyItems] });
  };

  const activeData = list[index];
  useUpdateEffect(() => {
    if (activeData) {
      const { itemName, templateDetailId, workers } = activeData
      setModel({
        applyItems: [
          {
            files: [],
            templateDetailId,
            workerType: itemName,
            workerPayItems: workers?.map(e => ({ ...e }))
          }
        ]
      })
    }
  }, [activeData])


  console.log('model', model)

  return (
    <Page
      footerSticky
      slotFooter={
        <ByButton
          size="large"
          className="w-2/3"
          loading={loading}
          onClick={() => submit()}
        >
          发起
        </ByButton>
      }
    >
      <CustomerCard source={data} />

      <View className="m-3">
        <TabsTag mode="auto" items={list} active={index} className="overflow-auto" onChange={setIndex} />
      </View>

      <View className="px-3">
        <Card>
          <ByRow wrap>
            <ByCol span={6}>
              <RowTitle title="付款类别" />
              {/* <View>{workerType}</View> */}
              <View>{activeData?.label}</View>
            </ByCol>

            <ByCol span={6}>
              <RowTitle title="项目阶段" />
              <View>{model.constructionProjectName}</View>
            </ByCol>
          </ByRow>
        </Card>

        <ByRow align="center" className="my-3">
          <ByText>总额：</ByText>
          <ByText type="primary">{activeData?.paidAmount}</ByText>
        </ByRow>

        <Card>
          <ByRow className="text-sm text-second">
            <ByCol span={3}>收款对象</ByCol>
            <ByCol span={5}>{activeData?.itemName}</ByCol>
            <ByCol span={4}>已工作</ByCol>
          </ByRow>

          {
            model.applyItems[0]?.workerPayItems?.map(item => (
              <WorkerPayItem
                key={index + "_" + item.workerId}
                source={item}
                attendance={attendanceMapHandler.get(item.workerId)}
              />
            ))
          }
        </Card>

        <ByCellGroup className="mt-4">

          <ByCell label="备注" vertical>
            <FormInput
              showLimitWords
              maxlength={120}
              type="textarea"
              value={model.remark}
              placeholder="请输入"
              onChange={(e) => setModel({ remark: e })}
            />
          </ByCell>

          <ByCell label="附件" vertical>
            <ByImageGroup
              showDelete
              urls={model.applyItems[0]?.files}
              onChange={(e) => deleltePics(index, e)}
              slotFooter={
                <Uploader
                  size={140}
                  onSuccess={(e) => updatePics(index, e)}
                />
              }
            />
          </ByCell>
        </ByCellGroup>

        <ByCellGroup className="mt-4" title="流程">
          <View className="py-3">
            {workflowList[0]?.steps.map((item) => (
              <ByStepsItem
                key={item.nodeId}
                title={item.nodeName}
                date={item.approvers.length > 0 ? "1人通过即可" : ""}
              >
                <BySpace gap={8}>
                  {item.approvers.map((approver) => (
                    <ByTag key={approver.actorId} {...tagProps}>
                      {approver.actorName}
                    </ByTag>
                  ))}
                </BySpace>
              </ByStepsItem>
            ))}
          </View>
        </ByCellGroup>
      </View>
    </Page>
  );
};
